/**
 * Copyright (c) D.L..
 */
package filePath;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * copy recursively
 *
 * @author D.L.
 */
public class CopyRecursively {

	static void cp(File src, File tbase) throws IOException {
		Path srcPath = src.toPath();
		Path tPath = tbase.toPath();
		if (src.isDirectory()) {
			if (tbase.isDirectory()) {
				File tsd = tPath.resolve(srcPath.getFileName()).toFile();
				tsd.mkdir();
				// process each file and sub directory
				for (File sub : src.listFiles()) {
					cp(sub, tsd);
				}
			} else {
				// target not directory
				throw new RuntimeException();
			}
		} else if (src.isFile()) {
			File tf = tbase;
			if (tbase.isDirectory()) {
				// create file with same name
				tf = tPath.resolve(srcPath.getFileName()).toFile();
			} else {
				// different file name
			}
			tf.createNewFile();
			cpf(src, tf);
		} else {
			// ignored
		}
	}

	static void cpf(File src, File target) throws IOException {
		int read = 0;
		try (InputStream in = new FileInputStream(src);
			 OutputStream out = new FileOutputStream(target)) {

			while ((read = in.read(buf)) != -1) {
				out.write(buf, 0, read);
			}
		}
	}

	public static void main(String[] args) throws Exception {
		Path src = Paths.get(args[0]);
		Path target = Paths.get(args[1]);
		cp(src.toFile(), target.toFile());
	}

	static byte[] buf = new byte[8 * 1024 * 64]; // 64kB

	/**
	 *
	 */
	private CopyRecursively() {
	}

}
